<template>
  <div class="goods-container">
    <!-- 筛选条件 -->
    <div class="filter-content">
      <div class="filter-btn">
        <div class="filter-title">
          <i class="el-icon-search"></i>
          <span class="">筛选搜索</span>
        </div>
        <div>
          <el-button size="small" @click="resetFilter">重置</el-button>
          <el-button type="primary" size="small" @click="submitFilter" :loading="filterLoading">查询结果</el-button>
        </div>
      </div>
      <div class="filter-form">
        <!-- 商品编号 -->
        <div class="filter-item">
          <div>
            <span>订单编号：</span>
            <el-input placeholder="请输入订单编号" v-model="orderNo"> </el-input>
          </div>
        </div>
        <!-- 收货人信息 -->
        <div class="filter-item">
          <div>
            <span>收货人：</span>
            <el-input placeholder="收货人姓名/电话" v-model="nameOrPhone"> </el-input>
          </div>
        </div>
        <!-- 订单状态 -->
        <div class="filter-item">
          <div>
            <span>订单状态：</span>
            <el-cascader v-model="selectValue" :options="selectOptions" placeholder="请选择订单状态"></el-cascader>
          </div>
        </div>
      </div>
    </div>
    <!-- 数据列表 -->
    <div class="goods-title">
      <div>
        <i class="el-icon-tickets"></i>
        <span style="margin-left: 5px">数据列表</span>
      </div>
    </div>
    <!-- 数据表格 -->
    <div class="goods-list">
      <el-table :data="tableData.list" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection"> </el-table-column>
        <el-table-column prop="id" label="编号"> </el-table-column>
        <el-table-column prop="orderNo" label="订单编号"></el-table-column>
        <el-table-column prop="createTime" label="提交时间" />
        <el-table-column prop="orderPrice" label="订单金额"> </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态"> </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="router.push('/home/order/info/' + scope.row.id)">查看详情</el-button>
            <el-button size="small" type="danger" :loading="scope.row.loading" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页导航 -->
      <div class="pagination-container">
        <div class="option-container">
          <div>
            <el-select v-model="value" placeholder="批量操作">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </div>
          <div class="btn">
            <el-button type="primary" @click="setRecommendOrNew" :loading="selectLoading">确定</el-button>
          </div>
        </div>
        <div class="pagination"><el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background> </el-pagination></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'

// 创建路由对象
const router = useRouter()

const options = reactive([
  {
    // 下拉菜单选项
    value: 'deliver',
    label: '批量发货'
  },
  {
    value: 'delete',
    label: '批量删除'
  }
])
let selectOptions = reactive([
  { value: 0, label: '待支付' },
  { value: 1, label: '待发货' },
  { value: 2, label: '待收货' },
  { value: 3, label: '已完成' }
])
let selectValue = reactive([]) // 筛选条件选中选项
let tableData = reactive({ list: [] }) // 表格显示数据
let selectLoading = ref(false)
let value = ref('') // 批量操作选中的value
let nameOrPhone = ref('') // 筛选条件收获人信息
let orderNo = ref('') // 筛选条件订单编号
let total = ref(0) // 总共有多少条数据
let pageSize = ref(5) //每页显示的数据
let currentPage = ref(1) // 当前页
let multipleSelection = reactive([]) // 表格中选中的订单数据
let allOrderList = reactive([]) // 保存所有的订单数据
let filterLoading = ref(false)

// 重置筛选条件
const resetFilter = () => {
  selectValue = ref([])
  nameOrPhone.value = ''
  orderNo.value = ''
}
// 处理请求到的表格数据
const dealOrderData = () => {
  for (let i = (currentPage.value - 1) * 5; i < currentPage.value * pageSize.value; i++) {
    if (allOrderList[i]) {
      const date = new Date(allOrderList[i].create_time)
      let status = allOrderList[i].order_status == 0 ? '等待买家支付' : allOrderList[i].order_status == 1 ? '等待商家发货' : allOrderList[i].order_status == 2 ? '等待买家收货' : '已完成'
      tableData.list.push({
        id: allOrderList[i].id,
        orderNo: allOrderList[i].order_id,
        createTime: date.toLocaleDateString() + ' ' + date.toLocaleTimeString(),
        orderPrice: '￥' + allOrderList[i].goods_num * allOrderList[i].goods_price,
        orderStatus: status,
        loading: false
      })
    } else {
      break
    }
  }
}
// 获取订单列表
const getOrderList = async () => {
  try {
    const data = await axios.get('/bus/get/order/list')
    if (data.code === 0) {
      // 获取成功
      ElMessage({
        type: 'success',
        message: data.msg
      })
      total.value = data.data.length
      allOrderList = data.data
      dealOrderData()
    } else if (data.code === 403 || data.msg === '身份认证错误') {
      ElMessage({
        type: 'error',
        message: data.msg
      })
      localStorage.removeItem('bus_token')
      router.replace('/login')
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch (err) {
    console.log(err)
    ElMessage.error(err)
  }
}

// 表格选中处理函数
const handleSelectionChange = (val) => {
  multipleSelection = val
}

// 切换页数
const handleCurrentChange = (val) => {
  currentPage.value = val
  tableData.list = []
  // 根据当前页和每一页长度进行数据渲染
  dealOrderData()
}
// 切换每一页显示的长度
const handleSizeChange = (val) => {
  pageSize.value = val
  tableData.list = []
  // 根据当前页和每一页长度进行数据渲染
  dealOrderData()
}

// 批量操作订单
const setRecommendOrNew = async () => {
  // 必须选择一项
  if (value.value === '') return ElMessage({ type: 'error', message: '请选择操作选项！' })
  // 必须有商品选中
  if (multipleSelection.length === 0) return ElMessage({ type: 'error', message: '至少选择一件商品！' })
  let flag = false // 记录是否存在未完成订单
  let deliverFlag = true
  multipleSelection.some((item) => {
    if (item.orderStatus !== 3 && value.value === 'delete') {
      flag = true
      return true
    }
    if (item.orderStatus !== 1 && value.value === 'deliver') {
      deliverFlag = false
      return true
    }
  })
  // 判断删除的订单是否全部完成
  if (flag && value.value === 'delete')
    return ElMessage({
      type: 'warning',
      message: '要删除的订单中存在未完成订单！'
    })

  // 判断发货的订单中是否全部是待发货的
  if (!deliverFlag && value.value === 'deliver')
    return ElMessage({
      type: 'warning',
      message: '存在订单已发货或买家未支付订单或已完成，请检查后重试！'
    })
  // 创建商品id
  let ids = ''
  multipleSelection.forEach((item) => {
    ids += item.id + ','
  })
  ids = ids.slice(0, -1)
  // 创建请求参数
  let params = { ids }
  switch (value.value) {
    case 'deliver':
      params = { ids, option: 'deliver' }
      break
    case 'delete':
      params = { ids, option: 'delete' }
      break
    default:
      ElMessage({ type: 'error', message: '选项错误！' })
  }
  selectLoading.value = true
  console.log(params)
  try {
    const data = await axios.post('/bus/deal/order/option', params)
    tableData.list = []
    if (data.code === 0) {
      // 更新数据成功
      ElMessage({ type: 'success', message: data.msg })
      getOrderList()
      // 重新获取订单数据
    } else {
      ElMessage({ type: 'error', message: data.msg })
    }
  } catch {
    ElMessage.error('请求失败！')
  } finally {
    selectLoading.value = false
  }
}

// 删除订单
const handleDelete = async (row) => {
  ElMessageBox.confirm('该订单还未完成，确认要删除吗？', '删除订单', {
    confirmButtonText: '确 定',
    cancelButtonText: '取 消',
    type: 'warning'
  })
    .then(async () => {
      row.loading = true
      try {
        const data = await axios.post('/bus/del/order', {
          id: row.id
        })
        console.log(data)
        if (data.code === 0) {
          // 删除成功
          ElMessage({
            type: 'success',
            message: data.msg
          })
          // 重新获取商品列表
          getOrderList()
        } else {
          // 删除失败
          ElMessage({
            type: 'error',
            message: data.msg
          })
        }
      } catch {
        ElMessage.error('请求失败！')
      } finally {
        row.loading = false
      }
    })
    .catch(() => {})
}

// 提交筛选条件筛选订单数据
const submitFilter = async () => {
  // 创建请求参数
  filterLoading.value = true
  // 验证商品货号是否正确
  if (orderNo.value !== '' && !/^[A-Za-z]{1,}\d+/.test(orderNo.value)) {
    return ElMessage({
      type: 'error',
      message: '商品货号为数字字母组合，且字母在前，数字在后！'
    })
  }
  try {
    const data = await axios.get('/bus/filter/order/list', {
      params: {
        orderNo: orderNo.value,
        nameOrPhone: nameOrPhone.value,
        OrderStatus: selectValue[0]
      }
    })
    if (data.code === 0) {
      // 获取成功
      ElMessage({
        type: 'success',
        message: data.msg
      })
      // 对数据进行处理
      total.value = data.data.length
      currentPage.value = 1
      allOrderList = data.data
      tableData.list = []
      dealOrderData()
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch {
    ElMessage.error('请求失败！')
  } finally {
    filterLoading.value = false
  }
}
getOrderList()
</script>

<style lang="scss" scoped>
.goods-container {
  padding: 50px;

  .filter-content {
    padding: 15px;
    min-width: 1120px;
    border: 1px solid #e1e1e1;

    .filter-btn {
      display: flex;
      justify-content: space-between;

      .filter-title {
        span {
          margin-left: 5px;
        }
      }
    }
    .filter-form {
      margin-top: 15px;
      padding: 0 30px;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
    }

    .filter-item {
      width: 26%;
      margin-bottom: 10px;

      div {
        display: flex;
        align-items: center;

        span {
          white-space: nowrap;
        }
      }
    }
  }
  .goods-title {
    padding: 15px;
    margin-top: 30px;
    min-width: 1120px;
    border: 1px solid #e1e1e1;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .goods-list {
    margin-top: 30px;
    min-width: 1120px;
    background-color: #fff;
    :deep(.el-table .el-table__cell) {
      text-align: center;
    }

    .pagination-container {
      margin-top: 15px;
      display: flex;
      justify-content: space-between;

      .option-container {
        display: flex;
        align-items: center;

        .btn {
          margin-left: 15px;
        }
      }
    }
  }
}
</style>
